import axios from 'axios';
import fs from 'fs';
import path from 'path';
import dayjs from 'dayjs';
import mqtt from 'mqtt';
import { connectOptions } from './use_mqtt.js'

const hostUrl = 'http://111.8.86.3:19126'
let topic = 'third-party/XTZXYYSBY001/v2/up/report'
let token = ''

const options = {
  clientId: 'mqttx_011c6c1e',
  username: 'thinker',
  password: '123456',
  clean: true,
  connectTimeout: 4000,
  reconnectPeriod: 3000
}
const { protocol, host, port } = connectOptions

let connectUrl = `${protocol}://${host}:${port}`
// 连接mqtt服务器
const client = mqtt.connect(connectUrl, options)
// client.on('connect', () => {
//   console.log(`${host}: 连接成功。。。。。`)
// })

const optionList = [
  { fmAddress: '2111222166', meterId: '922343', deviceCode: 'XT200025' },
  { fmAddress: '2009210933', meterId: '139', deviceCode: 'XT200026' },
  { fmAddress: '2111222161', meterId: '922333', deviceCode: 'XT200028' },
  { fmAddress: '22020103208', meterId: '1282833', deviceCode: 'XT220498' },
]
const delayedLog = (item, index) => new Promise(resolve => {
  setTimeout(() => {
    getData(item.fmAddress, item.meterId, item.deviceCode)
    resolve();
  }, index * 2000);
});
let userName = 'yh_zhongxyy';
let userId = '1990'
let dateTime = '';
const downloadImage = async () => {
  dateTime = dayjs().valueOf();
  // 图片的URL
  const imageUrl = hostUrl + '/api/auth/verificationCode/captcha-image/' + dateTime;
  // 本地保存路径
  const localPath = path.join(`./img/${dateTime}.jpg`);
  return axios({
    method: 'get',
    url: imageUrl,
    responseType: 'stream' // 重要：设置为stream以处理大文件或流式数据
  })
    .then(function (response) {
      // 在指定路径创建一个写入流
      const writer = fs.createWriteStream(localPath);
      // 将获取到的数据流重定向到写入流
      response.data.pipe(writer);
      return new Promise((resolve, reject) => {
        writer.on('finish', resolve);
        writer.on('error', reject);
      });
    })
    .then(() => {
      console.log('图片下载并保存成功', localPath);
      return localPath
    })
    .catch(error => {
      console.error('下载或保存图片时发生错误:', error);
      return false
    });

}

const postAliyun = async (localPath) => {
  let aliurl = 'https://tysbgpu.market.alicloudapi.com/api/predict/ocr_general';
  // let aliurl = 'https://gjbsb.market.alicloudapi.com/ocrservice/advanced';
  const appcode = "f8330a3b0445497a8b916d7519ea1fed";
  // const localPath = path.join(`./img/${localPath}.jpg`);
  let filePath = path.resolve(localPath)
  let imageFile = fs.readFileSync(filePath);
  imageFile = new Buffer(imageFile).toString('base64');
  let vcode = '';

  const imageBase64 = 'data:image/jpeg;base64,' + imageFile;
  // console.log('本地图片转成base64', imageBase64);
  const params = {
    "image": imageBase64,
    "configure": {
      "min_size": 16,
      "output_prob": true,
      "output_keypoints": false,
      "skip_detection": false,
      "dir_assure": false,
      "language": "sx"
    }
  }
  // 调用阿里云通用识别图片API
  return axios.post(aliurl, JSON.stringify(params), {
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
      "Accept": "application/json",
      "Authorization": "APPCODE " + appcode
    }
  }).then((data) => {
    if (data.data.success) {
      console.log("识别验证码结果:", data.data.ret)
      if (data.data.ret[0].word.length === 4) {
        vcode = data.data.ret[0].word;
        return vcode
      } else {
        console.log("识别失败")
        return false
      }
    }
  })
    .catch((error) => {
      console.error('error:', error)
      return false
    });
};

const getData = async (fmAddress, meterId, deviceCode) => {
  console.log(fmAddress, meterId, deviceCode)
  const params = new URLSearchParams();
  const startDate = dayjs().subtract(1, 'day').startOf('day').valueOf();
  const endOfDay = dayjs().endOf('day').valueOf(); // 获取今天的结束时间
  params.append("startDate", startDate.toString());
  params.append("endDate", endOfDay.toString());
  params.append("fmAddress", fmAddress);
  params.append("meterId", meterId);
  let url = hostUrl + '/api/largeCustomer/operationManagement/meterRealTimeDataTable?' + params.toString();
  fetch(url, {
    method: 'get',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'Accept': 'application/json, text/plain, */*',
      'Tw-Authorization': token,
      'Cookie': `userId=${userId}; userName=${userName}; TW-Authorization=${token};`
    }
  })
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log(data.message, '请求数据返回');
      if (!data.code) {
        const tableData = [...data.data.table].slice(0, 33);
        if (tableData.length === 0) {
          console.log('今日数据不存在，自动发送0数据')
          return
        }
        for (let i = 0; i < tableData.length; i++) {
          const dt = dayjs(tableData[i].readTime);
          if (dt.minute() === 0) {
            const totalFlux = tableData[i].totalFlux
            const dateTime = 'T_' + tableData[i].readTime;
            let obj = {
              "deviceCode": deviceCode
            };
            obj[`${dateTime}`] = {
              "datas": {
                "internetTraffic": totalFlux,
              }
            }
            const payload = [obj]
            const qos = 0
            client.publish(topic, JSON.stringify(payload), { qos }, (error) => {
              if (error) {
                console.error(error, '发送错误')
              }
              console.log(`${dayjs(tableData[i].readTime).format("YYYY-MM-DD HH:mm:ss")}发送成功, 设备编号${deviceCode},流量 ${totalFlux}`)
            })
          }
        }

      } else {
        console.log('获取数据错误，token失效！！重新登录');
        setTimeout(() => {
          handleLogin()
        }, 3000);
      }
    })
    .catch((error) => console.error('error:', error));
}


const handleLogin = async () => {
  const url = hostUrl + '/api/auth/jwt/token'
  let code = ''
  let imgSrc = await downloadImage()
  console.log('本地的图片路径', imgSrc)
  if (imgSrc) {
    code = await postAliyun(imgSrc);
    if (code) {
      let params = {
        key: dateTime,
        loginName: userName,
        password: '40233af31b41b8101d5a194a78fe139b',
        verificationCode: code,
      }
      axios.post(url, params, {
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'Accept': 'application/json, text/plain, */*',
        }
      }).then((data) => {
        console.log(data.data, '登录接口返回');
        if (!data.data.code && data.data.data.token) {
          token = data.data.data.token
          console.log("获取token成功", token);
          // 登录成功后请求接口 获取所有用户信息, 获取设备列表信息, 向所有设备发送数据
          setTimeout(() => {
            Promise.all(optionList.map(delayedLog)).then(() => {
              console.log('获取数据中...');
            });
          }, 2000);
        } else if (data.data.code === -1 && data.data.message === '验证码错误') {
          console.log('验证码错误,重新获取验证码');
          setTimeout(() => {
            handleLogin()
          }, 1000 * 10);
        } else {
          console.log('接口 500！！！！ 防呆保护！！！一个小时一次');
          setTimeout(() => {
            handleLogin()
          }, 1000 * 60 * 60);
        }
      }).catch((err) => {
        console.log("请求错误:" + err)
        // 检查代码问题  不然登录死循环
      });

    } else {
      console.log("未识别验证码,重新获取验证码");
      setTimeout(() => {
        handleLogin()
      }, 5000);
    }
  } else {
    console.log("获取图片失败，重新获取图片");
    setTimeout(() => {
      handleLogin()
    }, 5000);
  }
};
// 倒计时定时器每次 登录操作  完成后请求数据发送
let second = 10; // 初始获取时间 秒
const minute = 480; // 间隔获取时间 分钟
setInterval(() => {
  second--
  if (second === 0) {
    console.log('获取数据中...');
    handleLogin()
    second = minute * 60
  } else {
    console.log("倒计时" + second + "秒...再次登录获取数据");
  }
}, 1000);









